<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="580px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="12">
          <el-form-item label-width="80px" label="销售单号" prop="mofSodh">
            <el-input
              v-model="queryParams.mofSodh"
              placeholder="请输入销售单号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="80px" label="制造单号" prop="mofZzdh">
            <el-input
              v-model="queryParams.mofZzdh"
              placeholder="请输入销售单号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="125px" prop="mofWldm">
            <span slot="label">
              <el-tooltip
                content="综合查询包含物料代码，品名规格，客户编码查询"
                placement="top"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
              综合查询
            </span>
            <el-input
              v-model="queryParams.mofWldm"
              clearable
              size="small"
              style="width: 400px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          v-hasPermi="['produce:MaterialCheck:query']"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['produce:materialScheduling:add']"
        >
          计划导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-position"
          size="mini"
          @click="handleAutoSchedule"
          v-hasPermi="['produce:MaterialCheck:query']"
        >
          自动排程
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDet"
          v-hasPermi="['produce:MaterialCheck:rollback']"
        >
          删除
        </el-button>
      </el-col>
      <br />
      <br />
      <div style="color: blue">
        <p>提示：排程前请注意以下条件是否维护完毕</p>
        <p style="margin-left: 40px">
          1、生产日历是否维护OK？2、机台特性是否维护OK？3、排程参数是否设置OK？
        </p>
        <p style="margin-left: 40px">
          4、料件的材质与颜色是否维护OK？5、模具与料件的对应关系及产品穴数与成型时间是否设置OK？
        </p>
      </div>
    </el-row>
    <!-- 表格数据 -->
    <el-table
      highlight-current-row
      v-loading="loading"
      :data="mofMstrList"
      border
      stripe
      height="calc(100% - 200px)"
      ref="somTable"
      @row-click="clickRow"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column
        label="客户编码"
        :show-overflow-tooltip="true"
        fixed="left"
        width="120"
        align="center"
        prop="mofCustomer"
      />
      <el-table-column
        label="物料代码"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="mofWldm"
      />
      <el-table-column
        label="品名规格"
        :show-overflow-tooltip="true"
        width="230"
        align="center"
        prop="mofPmgg"
      />
      <el-table-column
        label="计划数量"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mofZzsl"
      />
      <el-table-column
        label="成型时间"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mofCxsj"
      />
      <el-table-column
        label="预计工时"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mofEstimatedWorkingHours"
      />
      <el-table-column
        label="模具编号"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="mofMjbh"
      />
      <el-table-column
        label="模具名称"
        :show-overflow-tooltip="true"
        width="230"
        align="center"
        prop="mofMjmc"
      />
      <el-table-column
        label="模具状态"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mofMoldStatus"
      >
        <template #default="scope">
          <dict-tag
            :options="mouldStatusOptions"
            :value="scope.row.mofMoldStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="完工日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="mofWgrq"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.mofWgrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="销售单号"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="mofSodh"
      />
      <el-table-column
        label="制造单号"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="mofZzdh"
      />
      <el-table-column
        label="穴数"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="mofXs"
      />
    </el-table>

    <!-- 计划导入 -->
    <el-dialog v-model="open" :fullscreen="true" append-to-body>
      <el-form
        :model="queryParamsDia"
        ref="queryFormDia"
        :inline="true"
        label-width="68px"
      >
        <el-row>
          <el-col :span="18">
            <el-form-item label="综合查询" label-width="100px" prop="somDjbh">
              <span slot="label">
                <el-tooltip
                  content="综合查询包含销售单号，客户编码，物料代码查询"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                综合查询
              </span>
              <el-input
                v-model="queryParamsDia.somDjbh"
                placeholder="综合查询包含销售单号，客户编码，物料代码"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item label="发货时间" prop="dateRange">
              <el-date-picker
                clearable
                size="small"
                v-model="dateRange"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>

            <el-form-item style="margin-left: 50px">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQueryDia"
                >搜索</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <Page
              style="margin-right: 0px"
              :current="queryParamsDia.pageNum"
              :page-size="queryParamsDia.pageSize"
              :total="planTotal"
              @on-change="pageChange"
              simple
            ></Page>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        highlight-current-row
        :row-style="iRowStyle"
        :header-row-style="iHeaderRowStyle"
        :header-cell-style="iHeaderCellStyle"
        v-loading="planLoading"
        :data="molList"
        height="calc(100% - 200px)"
        border
        stripe
        @row-click="clickRow"
        @selection-change="handleSelectionChangeC"
      >
        <el-table-column
          label="#"
          type="index"
          width="55"
          fixed="left"
          align="center"
        />
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
          align="center"
        />
        <el-table-column
          label="制造物料客户编码"
          :show-overflow-tooltip="true"
          align="center"
          fixed="left"
          prop="molCustomerCode"
        />
        <el-table-column
          label="制造物料编码"
          :show-overflow-tooltip="true"
          align="center"
          prop="molWldm"
        />
        <el-table-column
          label="制造物料品名规格"
          :show-overflow-tooltip="true"
          align="center"
          prop="molPmgg"
        />
        <el-table-column
          label="订单成品物料编码"
          :show-overflow-tooltip="true"
          align="center"
          prop="molFxdm"
        />
        <el-table-column
          label="订单成品品名规格"
          :show-overflow-tooltip="true"
          align="center"
          prop="molFxdmPmgg"
        />
        <el-table-column
          label="销售单号"
          :show-overflow-tooltip="true"
          align="center"
          prop="molSodh"
        />
        <el-table-column
          label="客户代码"
          :show-overflow-tooltip="true"
          align="center"
          prop="molKhdm"
        />
        <el-table-column
          label="采购属性"
          :show-overflow-tooltip="true"
          align="center"
          prop="molCgsx"
        >
          <template #default="scope">
            <dict-tag :options="bomCgsxOptions" :value="scope.row.molCgsx" />
          </template>
        </el-table-column>
        <el-table-column
          label="订单数量"
          :show-overflow-tooltip="true"
          align="center"
          fixed="right"
          prop="molDdsl"
        />
        <el-table-column
          label="库存数量"
          :show-overflow-tooltip="true"
          align="center"
          fixed="right"
          prop="molKcsl"
        />
        <el-table-column
          label="需求数量"
          :show-overflow-tooltip="true"
          align="center"
          fixed="right"
          prop="molXqsl"
        />
        <el-table-column
          label="可生产数量"
          :show-overflow-tooltip="true"
          width="100"
          align="center"
          fixed="right"
          prop="molScsl"
        >
          <template #default="scope">
            <el-input
              type="number"
              class="inputName"
              style="width: 80px"
              v-model="scope.row.molScsl"
              @input="changValue(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="完工日期"
          width="150"
          :show-overflow-tooltip="true"
          align="center"
          fixed="right"
          prop="molWgrq"
        >
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.molWgrq"
              type="date"
              class="inputName inputWith"
              style="width: 134px"
              placeholder="选择日期"
            ></el-date-picker>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllCustomer } from "@/api/project/customer";
import { getAllCgList } from "@/api/project/mstr";
import {
  addPlan,
  getPlan,
  listMof,
  autoSchedule,
  delMofMstr,
} from "@/api/produce/materialScheduling";

export default {
  name: "MaterialScheduling",
  data() {
    return {
      // 遮罩层
      tableH: document.body.clientHeight - 300,
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],

      //计划导入数据
      molList: [],
      // 明细计划自动排程list
      mofMstrList: [],

      //用来保存的Mol数组
      saveMolList: [],

      somDjbhs: [],

      //当前数据
      currentData: [],

      // 查询
      openSearch: false,

      //采购属性
      bomCgsxOptions: [],

      //未维护的材料明细
      NoneMaintain: [],
      //保存当前Som
      somData: [],
      // 日期范围
      dateRange: [
        this.$moment().startOf("month").toDate(),
        this.$moment().add(100, "year").endOf("month").toDate(),
      ],
      // 非单个禁用
      single: true,
      //选中的单据
      clickMof: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //计划导入总条数
      planTotal: 0,
      planLoading: true,
      // 营销订单维护表格数据
      somList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态标志字典
      somZtbzOptions: [],
      //根据客户代码查询出物料信息
      selectedItmMstr: [],
      // 订单类型字典
      somOrderZtbzOptions: [],
      //单位类型字典
      itmDwOptions: [],
      //模具状态字典
      mouldStatusOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        mofPcmflag: 0,
        mofQrflag: 0,
        mofSodh: null,
        mofZzdh: null,
        mofWldm: null,
      },

      //查询参数2
      queryParamsDia: {
        pageNum: 1,
        pageSize: 30,
        somDjbh: null,
        somCustwldm: null,
        somJhrqEnd: null,
        somJhrqBegin: null,
        somWldm: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.getList();

    //得到单位
    this.getDicts("sys_unit").then((response) => {
      this.itmDwOptions = response.data;
    });
    this.getDicts("mould_status").then((response) => {
      this.mouldStatusOptions = response.data;
    });

    //得到维护类型
    this.getDicts("material_matain_ztbz").then((response) => {
      this.somOrderZtbzOptions = response.data;
    });

    //得到采购属性
    getAllCgList().then((response) => {
      this.bomCgsxOptions = response.data;
      for (let i of this.bomCgsxOptions) {
        i.dictLabel = i.cgName;
        i.dictValue = i.cgId + "";
        i.listClass = "default";
      }
    });
  },
  methods: {
    tableRowClassName(row, rowIndex) {},
    iRowStyle: function ({ row, rowIndex }) {
      return "height:10px;";
    },
    iHeaderRowStyle: function ({ row, rowIndex }) {
      return "height:10px;";
    },
    iHeaderCellStyle: function ({ row, column, rowIndex, columnIndex }) {
      return "padding:0px;text-align:center";
    },

    /** 查询列表 */
    getList(row) {
      this.tableH = document.body.clientHeight - 280;
      this.loading = true;
      listMof(this.queryParams).then((response) => {
        this.mofMstrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    pageChange(page) {
      this.queryParamsDia.pageNum = page;
      if (this.dateRange !== null) {
        this.queryParamsDia.somJhrqBegin = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParamsDia.somJhrqEnd = this.moment(this.dateRange[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      } else {
        this.queryParamsDia.somJhrqBegin = null;
        this.queryParamsDia.somJhrqEnd = null;
      }
      getPlan(this.queryParamsDia).then((response) => {
        this.molList = [];
        this.molList = this.molList.concat(response.rows);
        this.planTotal = response.total;
        this.planLoading = false;
      });
    },
    handleSearch() {
      this.reset();
      this.title = "查询明细计划自动排程";
      this.openSearch = true;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.openSearch = false;
    },
    // 表单重置
    reset() {
      this.form = {
        molScsl: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },

    handleQueryDia() {
      this.molList = [];

      this.queryParamsDia.pageNum = 1;

      this.getPlanPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = null;
      this.queryParams.somJhrqBegin = null;
      this.queryParams.somJhrqEnd = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChangeC(selection) {
      this.ids = selection.map((item) => item.somId);
      this.somDjbhs = selection.map((item) => item.somDjbh);
      this.currentData = selection;
    },
    //打开计划导入界面
    handleAdd() {
      this.getPlanPage();
      this.title = "计划导入";
      this.open = true;
    },

    getPlanPage() {
      this.planLoading = true;
      this.queryParamsDia.pageNum = 1;
      if (this.dateRange !== null) {
        this.queryParamsDia.somJhrqBegin = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParamsDia.somJhrqEnd = this.moment(this.dateRange[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      } else {
        this.queryParamsDia.somJhrqBegin = null;
        this.queryParamsDia.somJhrqEnd = null;
      }
      getPlan(this.queryParamsDia).then((response) => {
        this.molList = [];
        this.molList = this.molList.concat(response.rows);
        this.planTotal = response.total;
        this.planLoading = false;
      });
    },
    clickRow(row) {
      this.single = true;
      if (row != null) {
        this.single = false;
        this.clickMof = row;
      }
    },
    load() {
      if (
        this.queryParamsDia.pageNum <
        Math.ceil(this.planTotal / this.queryParamsDia.pageSize)
      ) {
        // this.queryParamsDia.pageSize = 30
        this.queryParamsDia.pageNum++;
        getPlan(this.queryParamsDia).then((response) => {
          this.molList = this.molList.concat(response.rows);
          this.planTotal = response.total;
        });
      }
      return 0;
    },
    changValue(row) {
      if (row.molScsl > row.molXqsl - row.molQrsl) {
        this.msgError("不允许超过待生产数量");

        row.molScsl = row.molXqsl - row.molQrsl;
      }
    },

    submitForm() {
      if (this.currentData.length > 0) {
        addPlan(this.currentData).then((response) => {
          this.getPlanPage();
          this.getList();
        });
      } else {
        this.msgError("请勾选数据");
      }
    },
    //自动排程
    handleAutoSchedule() {
      autoSchedule().then((res) => {
        this.msgSuccess("成功~");
        this.getList();
      });
    },
    //删除
    handleDet() {
      const mofMstr = this.clickMof;
      this.$confirm(
        '是否确认删除制造单号: <"' + mofMstr.mofZzdh + '">及数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delMofMstr(mofMstr.mofId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .inputName {
  > .el-input__inner {
    line-height: 20px;
    height: 20px;
  }

  .el-input__prefix > .el-input__icon {
    line-height: 10px;
    height: 20px;
    /*color: #1ab394;*/
  }

  .el-input__suffix > .el-input__suffix-inner > .el-input__icon {
    line-height: 20px;
    height: 20px;
    /*color: #1ab394;*/
  }

  .el-input__inner {
    width: 134px !important;
    /*color: #1ab394;*/
  }
}
</style>
